package me.ingxin.android.permission2.view.impl

import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.WindowManager
import me.ingxin.android.permission2.R
import me.ingxin.android.permission2.databinding.PxDialogDefaultTipsBinding
import me.ingxin.android.permission2.supportSpecialPermissions

/**
 * Created on 2023/7/9 by yin
 */
open class DefaultTipsDialog(context: Context, private val permissions: List<String>) :
    DefaultDialog(context) {

    private lateinit var binding: PxDialogDefaultTipsBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = PxDialogDefaultTipsBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setupWindow()
        val message = getMessage(permissions)
        if (message.isNullOrEmpty()) {
            binding.tvContent.text = String.format(
                context.getString(R.string.px_tips_template), getPermissionStr(permissions)
            )
        } else {
            binding.tvContent.text = message
        }
        //清除掉dimAmount，不会改变状态栏颜色
        window?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
    }

    /**
     * 获取权限说明
     * @param permissions 申请的权限
     * @return 返回值无效时使用默认值
     */
    protected open fun getMessage(permissions: List<String>): CharSequence? {
        return null
    }

    private fun setupWindow() {
        window?.let {
            val param = it.attributes
            it.setGravity(Gravity.TOP)
            param.width = WindowManager.LayoutParams.MATCH_PARENT
            it.attributes = param
            it.decorView.setPadding(0, 0, 0, 0)
            it.setWindowAnimations(R.style.Px_Dialog_Animation)
        }
    }

    private fun getPermissionStr(permissions: List<String>): String {
        val tempSet = HashSet<String>()
        val sb = StringBuilder()
        val pm = context.packageManager

        permissions.forEach {
            val permissionGroup = getPermissionGroup(it)
            val isSpecial = it in supportSpecialPermissions && !tempSet.contains(it)
            if (isSpecial || (permissionGroup != null && !tempSet.contains(permissionGroup))) {
                val name = if (isSpecial) {
                    getSpecialPermissionName(it)
                } else {
                    pm.getPermissionGroupInfo(permissionGroup!!, 0).loadLabel(pm)
                }
                sb.append(name)
                sb.append("、")
                tempSet.add(permissionGroup ?: it)
            }
        }
        val message = if (sb.isNotEmpty()) {
            sb.substring(0, sb.length - 1)
        } else {
            sb.toString()
        }
        return message
    }

}